<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;

class Login extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {   
        if(request()->isPost()){
            $data=input('post.');
            $result=$this->logincheck($data);
            if(isset($result['mid'])){
                $log=array(
                    'mid'=>$result['mid'],
                    'ip'=>request()->ip(),
                    'logintime'=>time(),
                    'msg'=>$result['msg'],
                );
                $log_rows=db('loginlog')->where('mid',$result['mid'])->count();
                if ($log_rows==3) {
                   $min=db('loginlog')->where('mid',$result['mid'])->min('logintime');
                   db('loginlog')->where('mid',$result['mid'])->where('logintime',$min)->delete();
                }
                db('loginlog')->insert($log);
            }
            if ($result['code']==0) {
                $this->error($result['msg']);
            }
            $this->success('登录成功','admin/index/index');
        }
        if(session('loginname', '', 'admin') && session('loginid', '', 'admin')){
            $this->redirect('admin/index/index');
        }
        return view();
    }
    /**
     * 登录验证
     *  @param 验证的数据
     */
    protected function logincheck($data){
        $validate=validate('Manager');
        if (!$validate->scene('login')->check($data)) {
            // $this->error($validate->getError());
            return ['code'=>0,'msg'=>$validate->getError()];
        }
        $res=db('manager')->where('account',$data['account'])->find();
        if ($res['account']!=$data['account']) {
            // $this->error('用户名或密码不正确');
            return ['code'=>0,'msg'=>'用户名不存在'];
        }
        if (md5($data['password'])!=$res['password']) {
            // $this->error('用户名或密码不正确!');
            return ['code'=>0,'msg'=>'输入的密码不正确!','mid'=>$res['id']];
        }
        if(!$res['state']){
            // $this->error("账号已锁定，不允许登录！");  
            return ['code'=>0,'msg'=>'账号已锁定，不允许登录！','mid'=>$res['id']];
        }
        session('loginname',$res['account'],'admin');
        session('loginid',$res['id'],'admin');
        // $this->success('登录成功','admin/index/index');
        return ['code'=>1,'msg'=>'登录成功','mid'=>$res['id']];
    }
    /**
     * 退出登录
     */
    public function logout(){
        session(null,'admin');
        $this->success('退出成功','admin/login/index');
    }

   
}
